﻿using Consul;
using Micro.Core.Options;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Micro.Extensions.ServiceDiscovery
{
    public class ConsulRegisterService:IHostedService
    {
        IConsulClient _consulClient;
        ServiceDiscoveryOption _serviceInfo;
        public ConsulRegisterService(ServiceDiscoveryOption serviceDiscoveryOption, IConsulClient consulClient)
        {
            _serviceInfo = serviceDiscoveryOption;
            _consulClient = consulClient;

        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine($"start to register service {_serviceInfo.Id} to consul client ...");
            await _consulClient.Agent.ServiceDeregister(_serviceInfo.Id, cancellationToken);
            await _consulClient.Agent.ServiceRegister(new AgentServiceRegistration
            {
                ID = _serviceInfo.Id,
                Name = _serviceInfo.Name,// 服务名
                Address = _serviceInfo.IP, // 服务绑定IP
                Port = _serviceInfo.Port, // 服务绑定端口
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(_serviceInfo.RegistAfterTime),//服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(_serviceInfo.HealthCheckTime),//健康检查时间间隔
                    HTTP = $"{_serviceInfo.Schema}://{_serviceInfo.IP}:{_serviceInfo.Port}" + _serviceInfo.Health,//健康检查地址
                    Timeout = TimeSpan.FromSeconds(_serviceInfo.HealthCheckTimeOut)
                },
                Tags = new[] { $"urlprefix-/{_serviceInfo.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签，以便 Fabio 识别
            });
            Console.WriteLine("register service info to consul client Successful ...");
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _consulClient.Agent.ServiceDeregister(_serviceInfo.Id, cancellationToken);
            Console.WriteLine($"Deregister service {_serviceInfo.Id} from consul client Successful ...");
        }
    }
}
